import React, { PureComponent } from 'react'
import { withRouter } from "react-router-dom";
import { Button, Select } from "antd";
import SearchInput from "@common/presentational/SearchInput";
import CustomizeTableProvide, { CustomizeTable, CustomizeTablePagination } from "@common/presentational/CustomizeTable";
import { connect } from "react-redux";
import {
    getEmployeeList,
    getEmployeeInfo,
    getSuperAdmin
} from "@sagas/employee";
import { EMPLOYEE_STATUS } from '@constants/EmployeeStatus'
import { getQuery, handleQueryEqual, setQuery } from "@utils/setUrlQuery";
import DropdownMenu from "@common/presentational/DropdownMenu";
import EmployeeInviteModal from "@components/employee/modal/EmployeeInviteModal";
import DeleteModal from "@components/employee/modal/DeleteModal";
import DepartModal from "@components/employee/modal/DepartModal";
import ReEnrollModal from "@components/employee/modal/ReEnrollModal";
import ResetAdminModal from "@components/employee/modal/ResetAdminModal";
import BilinIcon from "@common/presentational/BilinIcon";
@withRouter
@connect(({ employee, user }) => ({
    userInfoInStore: user.userInfoInStore,
    employeeListMap: employee.employeeListMap,
    superAdmin: employee.superAdmin,
}), {
    getEmployeeList,
    getEmployeeInfo,
    getSuperAdmin
})

class EmployeeListPage extends PureComponent {
    constructor(props) {
        super(props);
        const { status, query = '' } = getQuery(props.history)
        this.state = {
            status: status || '',
            query: decodeURIComponent(query)
        }
        this.tableRef = React.createRef();
        this.employeeInviteModalRef = React.createRef()
        this.deleteModalRef = React.createRef()
        this.departModalRef = React.createRef()
        this.reEnrollModalRef = React.createRef()
        this.resetAdminModalRef = React.createRef()

        this.getTableInfo = this.getTableInfo.bind(this)
        this.goModify = this.goModify.bind(this)//编辑
        this.invite = this.invite.bind(this)//邀请加入
        this.depart = this.depart.bind(this)//离职
        this.reEnroll = this.reEnroll.bind(this)//恢复入职
        this.delete = this.delete.bind(this)//删除
        this.resetAdmin = this.resetAdmin.bind(this)//转让超管

        this.paginationInfo = {}
        this.columns = [{
            key: 'name',
            dataIndex: 'name',
            title: '员工',
        }, {
            key: 'mobile',
            dataIndex: 'mobile',
            title: '手机号',
        }, {
            key: 'role_name',
            dataIndex: 'role_name',
            title: '角色',
        }, {
            key: 'status',
            dataIndex: 'status',
            title: '状态',
            render: text => EMPLOYEE_STATUS[text]
        }, {
            key: 'operation',
            dataIndex: 'operation',
            title: '操作',
            render: (text, record) => {
                let dropList = [];
                if (record.status === 'valid') {
                    dropList.push({
                        key: 'depart',
                        name: '离职',
                    })
                }
                if (record.status === 'invalid') {
                    dropList.push({
                        key: 'reEnroll',
                        name: '恢复任职',
                    })
                }
                dropList.push({
                    key: 'delete',
                    name: '删除',
                })
                return (
                    <div className="flex-vertical-center">
                        <div data-id={record.emp_id} onClick={this.goModify} className="mgr-8 ft-hover">编辑</div>
                        {record.status === 'inviting' ? <div data-id={record.emp_id} onClick={this.invite} className="mgr-8 ft-hover">邀请加入</div> : null}
                        <DropdownMenu
                            dropdownList={dropList}
                            onClick={this.handleRowOperation.bind(this, record)}
                        >
                            <div className="ft-hover">更多</div>
                        </DropdownMenu>
                    </div>
                )
            }
        }]
    }

    componentDidMount() {
        this.props.getSuperAdmin()
    }

    handleValueChange(key, value) {
        this.setState({
            [key]: value
        }, this.initTable)
    }

    handleRowOperation(record, type) {
        switch (type) {
            case 'depart':
                this.depart(record)
                break;
            case 'reEnroll':
                this.reEnroll(record)
                break;
            case 'delete':
                this.delete(record)
                break;
            default:
                break;
        }
    }

    resetAdmin() {
        this.resetAdminModalRef.current?.show()
    }

    resetAdminCallback() {
        window.location.replace('/brand-list')
    }

    depart(record) {
        this.departModalRef.current?.show({
            id: record.emp_id
        })
    }

    reEnroll(record) {
        this.reEnrollModalRef.current?.show({
            id: record.emp_id
        })
    }

    delete(record) {
        this.deleteModalRef.current?.show({
            id: record.emp_id
        })
    }
    goModify(e) {
        e.preventDefault();
        e.stopPropagation();
        const { history } = this.props
        const { id } = e.currentTarget.dataset
        this.props.getEmployeeInfo({
            empId: id
        }, (res) => {
            history.push({
                pathname: `/employee/edit/${id}`,
                state: {
                    ...res
                }
            })
        })
    }

    initTable() {
        this.tableRef.current?.initPage()
    }

    getTableInfo({ current, pageSize } = this.paginationInfo) {
        this.paginationInfo = { current, pageSize }
        const { query, status } = this.state
        this.props.getEmployeeList({
            search: query,
            status,
            pageNo: current,
            pageSize,
        })
        this.setUrlQuery()
    }

    setUrlQuery() {
        const { current, pageSize } = this.paginationInfo
        const { history } = this.props
        const { query, status } = this.state
        let params = {
            query,
            status,
            pageNo: current,
            pageSize
        }
        handleQueryEqual(params, history) || setQuery(params, history)
    }

    invite(e) {
        e.preventDefault();
        e.stopPropagation();
        const { id } = e.currentTarget.dataset
        this.employeeInviteModalRef?.current?.show({
            empId: id
        })
    }

    goCreatePage() {
        const { history } = this.props
        history.push(`/employee/create`)
    }

    render() {
        const { employeeListMap, superAdmin, userInfoInStore } = this.props
        const { query, status } = this.state
        return (
                <div className="table-scroll-container employee-list-page">
                    <div className='super-admin flex-row-between'>
                        <div className='ft-clr-d'>
                            品牌超级管理员: {superAdmin.name} ({superAdmin.mobile})
                        </div>
                        { userInfoInStore.is_super_admin ? (
                            <div onClick={this.resetAdmin} className='clr-green cur-poi'>
                                转让超管
                            </div>
                        ) : null }
                    </div>
                    <div className="table-params page-params flex-row-between mgb-16">
                        <div className="flex-vertical-center">
                            <Button type="primary" className="button-small mgr-16" onClick={this.goCreatePage.bind(this)}><BilinIcon type="plus" className="ft-18 mgr-8"/>新建</Button>
                        </div>
                        <div className="flex-vertical-center">
                            <Select className="mgr-16"
                                style={{ width: '140px' }}
                                onChange={this.handleValueChange.bind(this, 'status')}
                                value={status}
                            >
                                <Select.Option key="all" value="">全部</Select.Option>
                                <Select.Option key="inviting" value="inviting">待加入</Select.Option>
                                <Select.Option key="valid" value="valid">正常</Select.Option>
                                <Select.Option key="invalid" value="invalid">离职</Select.Option>
                            </Select>
                            <SearchInput style={{ width: 240 }}
                                onChange={this.handleValueChange.bind(this, 'query')}
                                initValue={query}
                                value={query}
                                placeholder="员工名称、手机号"
                            />
                        </div>
                    </div>
                    <CustomizeTableProvide ref={this.tableRef} tableKey="productList" onChange={this.getTableInfo}>
                        <div className="table-list">
                            <CustomizeTable
                                columns={this.columns}
                                dataSource={employeeListMap.employees || []}
                                pagination
                            />
                        </div>
                        <div className="table-pagination">
                            <CustomizeTablePagination
                                total={employeeListMap.total}
                            />
                        </div>
                    </CustomizeTableProvide>
                    <EmployeeInviteModal ref={this.employeeInviteModalRef} />
                    <DeleteModal callback={this.getTableInfo} ref={this.deleteModalRef} />
                    <DepartModal callback={this.getTableInfo} ref={this.departModalRef} />
                    <ReEnrollModal callback={this.getTableInfo} ref={this.reEnrollModalRef} />
                    <ResetAdminModal ref={this.resetAdminModalRef} callback={this.resetAdminCallback.bind(this)}/>
                </div>
        )
    }
}

export default EmployeeListPage